<template>
  <div>
    <el-container class="login-container">
      <el-form
        ref="loginForm"
        :model="loginFormData"
        class="login-form"
        label-position="top"
        @keyup.enter="handleLogin"
      >
        <h2 class="login-title">系统登录</h2>

        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginFormData.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginFormData.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginFormData.captcha"
              placeholder="请输入验证码"
              prefix-icon="el-icon-picture"
              style="flex: 1"
            ></el-input>
            <img
              :src="'data:image/png;base64,' + captchaImageRef"
              class="captcha-image"
              alt="验证码"
              @click="handleCaptcha"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="rememberMeFlag">记住我</el-checkbox>
          &nbsp;
          <el-link type="primary" style="float: right">忘记密码?</el-link>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" style="width: 100%" :loading="loading" @click="handleLogin">
            登 录
          </el-button>
        </el-form-item>

        <div class="login-footer">
          <span>还没有账号? </span>
          <el-link type="primary">立即注册</el-link>
        </div>
      </el-form>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store'
import { requestCaptcha } from '@/api/auth'
import type { LoginFormData } from '@/api/auth'
import router from '@/router'

const storegeKeyForRememberMe = 'rememberedUser'
const authStore = useAuthStore()

// 登录表单数据
const loginFormData = ref<LoginFormData>({
  username: '',
  password: '',
  captcha: '',
})

onMounted(async () => {
  await handleCaptcha()
  const loginFormDataJson = localStorage.getItem(storegeKeyForRememberMe)
  if (!loginFormDataJson) {
    return
  }
  const existedLoginFormData = JSON.parse(loginFormDataJson)
  existedLoginFormData.captcha = ''
  loginFormData.value = existedLoginFormData
})

// 验证码图片(base64Code)
const captchaImageRef = ref('')

// 加载状态
const loading = ref(false)

const rememberMeFlag = ref(false)

// 登录表单验证规则
// const loginRules = {
//   username: [
//     { required: true, message: '请输入用户名', trigger: 'blur' },
//     { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
//   ],
//   password: [
//     { required: true, message: '请输入密码', trigger: 'blur' },
//     { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
//   ],
//   captcha: [
//     { required: true, message: '请输入验证码', trigger: 'blur' },
//     { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
//   ]
// };

// 处理登录
const handleLogin = async () => {
  try {
    loading.value = true
    await authStore.loginAction(loginFormData.value)
    ElMessage.success('登录成功')

    // 记住密码处理
    if (rememberMeFlag.value) {
      localStorage.setItem(storegeKeyForRememberMe, JSON.stringify(loginFormData))
    }

    router.push('/home')
  } catch (error) {
    await handleCaptcha()
    ElMessage.error((error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleCaptcha = async () => {
  try {
    const captchaImage = await requestCaptcha()
    captchaImageRef.value = captchaImage
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png')
    no-repeat center center;
  background-size: cover;
}

.login-form {
  width: 380px;
  padding: 30px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
  font-size: 24px;
  font-weight: bold;
}

.login-footer {
  margin-top: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-image {
  margin-left: 10px;
  height: 38px;
  cursor: pointer;
}
</style>
